package com.example.simpleforum.servlet;

import com.example.simpleforum.dao.PostDao;
import com.example.simpleforum.model.Post;
import com.example.simpleforum.model.User;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;

/**
 * 编辑帖子Servlet
 */
public class PostEditServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取当前登录用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            // 用户未登录，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        // 获取帖子ID
        String postIdStr = request.getParameter("id");
        if (postIdStr == null || postIdStr.trim().isEmpty()) {
            // 帖子ID为空，重定向到帖子列表页面
            response.sendRedirect(request.getContextPath() + "/PostListServlet");
            return;
        }
        
        try {
            int postId = Integer.parseInt(postIdStr);
            
            // 查询帖子详情
            PostDao postDao = new PostDao();
            Post post = postDao.findById(postId);
            
            if (post == null) {
                // 帖子不存在，重定向到帖子列表页面
                response.sendRedirect(request.getContextPath() + "/PostListServlet");
                return;
            }
            
            // 检查是否是帖子作者
            if (post.getUserId() != user.getId()) {
                // 不是帖子作者，无权编辑，重定向到帖子详情页面
                response.sendRedirect(request.getContextPath() + "/PostDetailServlet?id=" + postId);
                return;
            }
            
            // 将帖子信息存入请求属性
            request.setAttribute("post", post);
            
            // 转发到帖子编辑页面
            request.getRequestDispatcher("/postEdit.jsp").forward(request, response);
        } catch (NumberFormatException e) {
            // 帖子ID格式错误，重定向到帖子列表页面
            response.sendRedirect(request.getContextPath() + "/PostListServlet");
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取当前登录用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            // 用户未登录，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        // 获取表单数据
        String postIdStr = request.getParameter("id");
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        
        // 表单验证
        if (postIdStr == null || postIdStr.trim().isEmpty()) {
            // 帖子ID为空，重定向到帖子列表页面
            response.sendRedirect(request.getContextPath() + "/PostListServlet");
            return;
        }
        
        if (title == null || title.trim().isEmpty()) {
            request.setAttribute("error", "标题不能为空");
            request.getRequestDispatcher("/postEdit.jsp").forward(request, response);
            return;
        }
        
        if (content == null || content.trim().isEmpty()) {
            request.setAttribute("error", "内容不能为空");
            request.getRequestDispatcher("/postEdit.jsp").forward(request, response);
            return;
        }
        
        try {
            int postId = Integer.parseInt(postIdStr);
            
            // 查询帖子详情
            PostDao postDao = new PostDao();
            Post post = postDao.findById(postId);
            
            if (post == null) {
                // 帖子不存在，重定向到帖子列表页面
                response.sendRedirect(request.getContextPath() + "/PostListServlet");
                return;
            }
            
            // 检查是否是帖子作者
            if (post.getUserId() != user.getId()) {
                // 不是帖子作者，无权编辑，重定向到帖子详情页面
                response.sendRedirect(request.getContextPath() + "/PostDetailServlet?id=" + postId);
                return;
            }
            
            // 更新帖子信息
            post.setTitle(title);
            post.setContent(content);
            post.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            
            // 保存更新
            boolean success = postDao.updatePost(post);
            
            if (success) {
                // 更新成功，重定向到帖子详情页面
                response.sendRedirect(request.getContextPath() + "/PostDetailServlet?id=" + postId);
            } else {
                // 更新失败
                request.setAttribute("error", "更新失败，请稍后再试");
                request.setAttribute("post", post);
                request.getRequestDispatcher("/postEdit.jsp").forward(request, response);
            }
        } catch (NumberFormatException e) {
            // 帖子ID格式错误，重定向到帖子列表页面
            response.sendRedirect(request.getContextPath() + "/PostListServlet");
        }
    }
}